package com.atguigu.gulimall.order.service.impl;

import com.atguigu.gulimall.order.entity.OrderReturnReasonEntity;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.service.OrderItemService;



@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * queues:声明需要监听的队列
     *  1.Message message 原生消息详细信息
     *  2. T<发送的消息类型> OrderReturnReasonEntity content
     *  3.Cancel cancel; 当前传输信息通道
     *
     *  Queue:可以很多人来监听，只要收到消息，队列删除消息，而且只能有一个收到此消息。
     *  场景：
     *      1）、订单服务启动多个;同一个消息，只能有一个客户端收到
     *      2)、只有一个消息完全处理完，方法运行结束，我们就可以接受下一个消息
     */
    @RabbitListener(queues = {"amqpAdmin.queue"})
    public void recieveMessage(Message message, OrderReturnReasonEntity content, Channel channel) throws InterruptedException, IOException {
        //{"id":1,"name":"哈哈","sort":null,"status":null,"createTime":1610704126406}
        byte[] body = message.getBody();
        //消息头属性
        MessageProperties properties = message.getMessageProperties();
        System.out.println("接收消息:" + message + "====》内容：" + content);

        //手动确认签收ack
        long deliveryTag = message.getMessageProperties().getDeliveryTag();

        //签收货物，非批量模式
        try {
            //收货
            channel.basicAck(deliveryTag, false);
            System.out.println("签收货物。。。"+deliveryTag);
            System.out.println("消息处理完成=============="+content.getName());
        } catch (Exception e) {
            //网络中断或者宕机
            //退货
            channel.basicNack(deliveryTag, false, true);
            System.out.println("没有签收货物。。。"+deliveryTag);
        }



    }

}